//
//  LCCommon.m
//  lcs
//
//  Created by 张鹏 on 15/3/13.
//  Copyright (c) 2015年 张鹏. All rights reserved.
//

#import "LCCommon.h"
#import <UIKit/UIKit.h>
#import "DataTypeTranslate.h"
#import "Log.h"

@implementation LCCommon

+(NSString *)saveImage:(UIImage *)image
{
    __weak NSData *imagedata = UIImageJPEGRepresentation(image, 0.8);
    
    NSString *savedImagePath = [self genaretePicPath];
    
    [imagedata writeToFile:savedImagePath atomically:YES];
    return [savedImagePath copy];
}

+ (NSString *)genaretePicPath{
    
    NSString * picPath = [self getDirectoryForDocuments:@"pic"];
    NSString * picName = [NSString stringWithFormat:@"%@.jpg",[self curremtTimeStr]];
    NSString * fullPicPath  = [picPath stringByAppendingPathComponent:picName];
    return fullPicPath;
}

+ (NSString *)curremtTimeStr{
    
    NSDate * date = [NSDate date];
    NSTimeInterval time = [date timeIntervalSince1970];
    
    NSString * timeStr = [NSString stringWithFormat:@"%f",time];
    timeStr = [timeStr stringByReplacingOccurrencesOfString:@"." withString:@""];
    return timeStr;
}

+(NSString *)getDocumentPath
{
#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return documentsDirectory;
#else
    NSString* homePath = [[NSBundle mainBundle] resourcePath];
    return homePath;
#endif
}
+(NSString *)getDirectoryForDocuments:(NSString *)dir
{
    NSString* dirPath = [[self getDocumentPath] stringByAppendingPathComponent:dir];
    BOOL isDir = NO;
    BOOL isCreated = [[NSFileManager defaultManager] fileExistsAtPath:dirPath isDirectory:&isDir];
    if ( isCreated == NO || isDir == NO ) {
        NSError* error = nil;
        BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
        if(success == NO)
            LLog(@"create dir error: %@",error.debugDescription);
    }
    return dirPath;
}
+ (NSString *)getPathForDocuments:(NSString *)filename
{
    return [[self getDocumentPath] stringByAppendingPathComponent:filename];
}
+(NSString *)getPathForDocuments:(NSString *)filename inDir:(NSString *)dir
{
    return [[self getDirectoryForDocuments:dir] stringByAppendingPathComponent:filename];
}
+(BOOL)isFileExists:(NSString *)filepath
{
    return [[NSFileManager defaultManager] fileExistsAtPath:filepath];
}
+(BOOL)deleteWithFilepath:(NSString *)filepath
{
    return [[NSFileManager defaultManager] removeItemAtPath:filepath error:nil];
}
+(NSArray*)getFilenamesWithDir:(NSString*)dir
{
    NSFileManager* fileManager = [NSFileManager defaultManager];
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:dir error:nil];
    return fileList;
}



+ (UIColor *)getColor:(NSString *)hexColor
{
    if(hexColor.length < 6)
    {
        return [UIColor clearColor];
    }
    unsigned int red,green,blue;
    NSRange range;
    range.length = 2;
    
    range.location = 0;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
    
    
    range.location = 2;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
    
    range.location = 4;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
    UIColor *color = [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
    return color;
}

+(BOOL)checkIsEmptyString:(NSString *)str
{
    if (![str isKindOfClass:[NSString class]]) {
        return YES;
    }
    
    if (!str) {
        return YES;
    }
    
    return [str stringByReplacingOccurrencesOfString:@" " withString:@""].length == 0;
    
}

+(NSString *)getUnitNumber:(NSInteger)number
{
    NSString *result = [NSString stringWithFormat:@"%d",(int)number];
    double newNumber = number;
    double wan = 10000;
    double yi = 100000000;
    if (newNumber < wan) {
        return  result;
    }
    if (number / wan > 0) {
        result = [NSString stringWithFormat:@"%.1f万",newNumber / wan];
        result = [result stringByReplacingOccurrencesOfString:@".0" withString:@""];
    }
    if (number / yi > 0 && newNumber > yi) {
        result = [NSString stringWithFormat:@"%.3f亿",newNumber / yi];
    }
    return result;
}

+(void)saveToLocalWithName:(NSString *)pathName uid:(NSString *)uid obj:(NSObject *)obj{
    
    NSString *Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *totalName = [NSString stringWithFormat:@"%@%@",uid,pathName];
    
    NSString *filename = [Path stringByAppendingPathComponent:totalName];
    [NSKeyedArchiver archiveRootObject:obj toFile:filename];
}
+(NSObject *)getLocalWithName:(NSString *)pathName uid:(NSString *)uid{
    
    NSString *Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *totalName = [NSString stringWithFormat:@"%@%@",uid,pathName];
    
    NSString *filename = [Path stringByAppendingPathComponent:totalName];
    return [NSKeyedUnarchiver unarchiveObjectWithFile:filename];
}

+(NSString *)countNumAndChangeformat:(NSString *)num{
    int count = 0;
    long long int a = num.longLongValue;
    while (a != 0)    {        count++;        a /= 10;    }
    NSMutableString *string = [NSMutableString stringWithString:num];
    NSMutableString *newstring = [NSMutableString string];
    while (count > 3) {        count -= 3;
        NSRange rang = NSMakeRange(string.length - 3, 3);
        NSString *str = [string substringWithRange:rang];
        [newstring insertString:str atIndex:0];
        [newstring insertString:@"," atIndex:0];
        [string deleteCharactersInRange:rang];    }
    [newstring insertString:string atIndex:0];
    return newstring;
}


+(NSString *)strWithYuan:(NSString *)string{
    
    NSMutableString *str = [NSMutableString stringWithString:string];
    
    NSMutableString *result = [NSMutableString string];
    
    while (![LCCommon checkIsEmptyString:str.description]) {
        
        NSString *ss = [LCCommon strForMoney:str.integerValue];
        
        if ([ss rangeOfString:@"万"].location != NSNotFound || [ss rangeOfString:@"亿"].location != NSNotFound) {
            [str replaceCharactersInRange:[str rangeOfString:[NSString stringWithFormat:@"%d",ss.intValue]] withString:@""];
            
            [result appendString:ss];
            
        }else
        {
            
            if (ss.integerValue == 0) {
                
            }else
            {
                [result appendString:ss];
                [result appendString:@"元"];
            }
            break;
        }
        
    }
    
    
    
    return result;
}

+(NSString *)getStrWithMoney:(long long)money{
    
    long long wan = 10000;
    long long yi = 100000000;
    
    NSString *yiStr;
    NSString *wanStr;
    NSString *yuanStr;
    
    if (money /yi > 0) {
        
        int yizhi = (int)(money/yi);
        
        yiStr = [NSString stringWithFormat:@"%d亿",yizhi];
        
        long long yiContent = yizhi * yi;
        
        long long shengyuWan = money - yiContent;
        
        if (shengyuWan / wan > 0) {
            wanStr = [NSString stringWithFormat:@"%d万",(int)(shengyuWan/wan)];
            
            long long shengyuYuan = shengyuWan - ((int)(shengyuWan/wan))*wan;
            if (shengyuYuan > 0) {
                yuanStr = [NSString stringWithFormat:@"%d",(int)shengyuYuan];
            }
            
        }else {
            
            long long shengyuYuan = shengyuWan;
            if (shengyuYuan > 0) {
                yuanStr = [NSString stringWithFormat:@"%d",(int)shengyuYuan];
            }
            
        }
    }else{
        
        if (money / wan > 0) {
            wanStr = [NSString stringWithFormat:@"%d万",(int)(money/wan)];
            
            long long shengyuYuan = money - ((int)(money/wan))*wan;
            if (shengyuYuan > 0) {
                yuanStr = [NSString stringWithFormat:@"%d",(int)shengyuYuan];
            }
            
        }else{
            
            if (money > 0) {
                yuanStr = [NSString stringWithFormat:@"%d",(int)money];
            }
            
        }
    }
    
    
    NSString *total = [NSString string] ;
    if (yiStr) {
        total = [total stringByAppendingString:yiStr];
    }
    
    if (wanStr) {
        total = [total stringByAppendingString:wanStr];
    }
    
    if (yuanStr) {
        total = [total stringByAppendingString:yuanStr];
    }
    
    total = [total stringByAppendingString:@"元"];
    
    if ((!yiStr) && (!wan) && (!yuanStr)) {
        total = @"0元";
    }
    
    return total;
}

+(NSString *)strForMoney:(NSInteger)number
{
    NSString *result = [NSString stringWithFormat:@"%d",(int)number];
    NSInteger newNumber = number;
    NSInteger wan = 10000;
    NSInteger yi = 100000000;
    if (newNumber < wan) {
        return  result;
    }
    if (number / wan > 0) {
        result = [NSString stringWithFormat:@"%ld万",newNumber / wan];
        //        result = [result stringByReplacingOccurrencesOfString:@".0" withString:@""];
    }
    if (number / yi > 0 && newNumber >= yi) {
        result = [NSString stringWithFormat:@"%ld亿",newNumber / yi];
    }
    return result;
}

+(NSString *)getTimeStrWithTime:(long long)time{
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:time];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    //用[NSDate date]可以获取系统当前时间
    return [dateFormatter stringFromDate:date];
}
//获取message时间戳转换成时间

+(NSString *)getMessageTimeHMStrWithTime:(NSString*)timeStr{
    //因为我们系统时间戳是13位，我们显示不需要那么精确，需要除1000
    double lastactivityInterval = [timeStr doubleValue]/1000;
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:lastactivityInterval];
    NSString* dateString = [formatter stringFromDate:date];
    
    return dateString;
}


+(NSString *)getMessageTimeStrWithTime:(NSString*)timeStr{
    //因为我们系统时间戳是13位，我们显示不需要那么精确，需要除1000
    double lastactivityInterval = [timeStr doubleValue]/1000;

    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:lastactivityInterval];
    NSString* dateString = [formatter stringFromDate:date];
    
    return dateString;
}


+(NSString *)strWithMoney:(long long)money{
    NSString *str = [NSString stringWithFormat:@"%ld",(long)money];
    if ([str length] <= 4) {
        str = [NSString stringWithFormat:@"%ld元",(long)money];
    }else if( [str length] > 4 && [str length] <= 8){
        
    }
    return str;

}



+(NSString *)cmpstartTime:(long long)startTime andEndTime:(long long)endTime
{//dd天HH分mm秒
    NSString *str;
    NSDate *now = [NSDate date];
//    NSString *dateStr = [DataTypeTranslate dateToString:now withFormatterType:KDateFormatterTypeYMDHMS];
//    now = [DataTypeTranslate string2Date:dateStr withFormatterType:KDateFormatterTypeYMDHMS];
    long long time = endTime - now.timeIntervalSince1970;
    
    if (time<=0)
    {
        return @"";
    }
    
    int betweenDay = (int)(time / (60*60*24));
    
     int betweenHour;
    if (betweenDay>0)
    {
         betweenHour = (time % (betweenDay * 60 * 60 * 24))/(60*60);
    }
    else
    {
        betweenHour = (int)time/(60*60);
    }
   
    int betweenMu = (time % (60 * 60))/60;
    int betweenS = time % (60);
    
//    betweenDay = (int)(time / (24*60*60));
//    betweenHour = (int)((time % (24*60*60))/(60*60));
//    betweenMu = time % (60 * 60)/60;
//    betweenS = time % (60);
    
    betweenHour += betweenDay *24;
    
//    str = [NSString stringWithFormat:@"%d天%d小时%d分%d秒",betweenDay,betweenHour,betweenMu,betweenS];
    
    NSString *betweenHourStr = [self changeIntToStrWithZero:betweenHour];
    NSString *betweenMuStr = [self changeIntToStrWithZero:betweenMu];
    NSString *betweenSStr = [self changeIntToStrWithZero:betweenS];
    
//    if ([betweenHourStr integerValue]==72) {
//        betweenMuStr = @"00";
//        betweenSStr = @"00";
//    }
    
    str = [NSString stringWithFormat:@"%@:%@:%@",betweenHourStr,betweenMuStr,betweenSStr];
    if (betweenS < 0) {
        return @"";
    }
    return str;
}

//+ (NSString *)changeTimeToFormatTypeWithTimeStamp:(NSString *)timeStamp
//{
//    NSString *str;
//    
//    if ([timeStamp doubleValue]<0)
//    {
//        return @"";
//    }
//    long long time = [timeStamp longLongValue]/1000;
//    
//    int betweenDay = (int)(time / (60*60*24));
//    int betweenHour = (time % (betweenDay * 60 * 60 * 24))/(60*60);
//    int betweenMu = (time % (60 * 60))/60;
//    int betweenS = time % (60);
//    
//    betweenHour += betweenDay *24;
//    
//    NSString *betweenHourStr = [self changeIntToStrWithZero:betweenHour];
//    NSString *betweenMuStr = [self changeIntToStrWithZero:betweenMu];
//    NSString *betweenSStr = [self changeIntToStrWithZero:betweenS];
//    
//    str = [NSString stringWithFormat:@"%@:%@:%@",betweenHourStr,betweenMuStr,betweenSStr];
//    
//    return str;
//}
//
//+ (NSString *)changeFormatterTimeToStamp:(NSString *)time
//{
//    
//    return @"";
//}

+ (NSString *)changeIntToStrWithZero:(int)date
{
    if (date<10)
    {
        return [NSString stringWithFormat:@"0%d",date];
    }
    else
    {
        return [NSString stringWithFormat:@"%d",date];
    }
}
/**
 获取格式化时间，like "6月07日-6月14日 还剩1天2消失"
 */
+(NSString *)formatZcTime:(long long)startTime andEndTime:(long long)endTime
{
    NSString * leftTimeStr = [LCCommon cmpstartTime:startTime andEndTime:endTime];
    NSString * finalStr = [NSString stringWithFormat:@"%@",leftTimeStr];
    if ([LCCommon checkIsEmptyString:leftTimeStr]) {
        return @"已过期";
    }
    return finalStr;
}


@end
